<template>
  <!-- 背景容器 -->
  <div class="background-container"></div>

  <div class="auth-page">
    <!-- 标题区域 -->
    <div class="page-title">司机账号管理</div>

    <!-- 选项卡切换 -->
    <div class="tab-container">
      <button
        class="tab-btn"
        :class="{ active: currentTab === 'register' }"
        @click="switchTab('register')"
      >
        账号注册
      </button>
      <button
        class="tab-btn"
        :class="{ active: currentTab === 'login' }"
        @click="switchTab('login')"
      >
        账号登录
      </button>
    </div>

    <!-- 注册表单 -->
    <div v-if="currentTab === 'register'" class="form-card">
      <div class="form-item">
        <label class="form-label">手机号</label>
        <input
          type="tel"
          v-model="registerForm.phone"
          placeholder="请输入11位手机号"
          maxlength="11"
          class="form-input"
          @input="validatePhone(registerForm.phone, 'register')"
        />
        <span v-if="registerErrors.phone" class="error-text">{{
          registerErrors.phone
        }}</span>
      </div>

      <div class="form-item">
        <label class="form-label">验证码</label>
        <div class="code-input-group">
          <input
            type="text"
            v-model="registerForm.code"
            placeholder="请输入6位验证码"
            maxlength="6"
            class="form-input code-input"
          />
          <button
            class="send-code-btn"
            @click="sendRegisterCode"
            :disabled="registerCountdown > 0 || !isPhoneValid('register')"
          >
            {{
              registerCountdown > 0
                ? `${registerCountdown}s后重发`
                : "发送验证码"
            }}
          </button>
        </div>
      </div>

      <div class="form-item">
        <label class="form-label">设置密码</label>
        <input
          type="password"
          v-model="registerForm.password"
          placeholder="6-16位密码，含数字和字母"
          class="form-input"
          @input="validatePassword(registerForm.password)"
        />
        <span v-if="registerErrors.password" class="error-text">{{
          registerErrors.password
        }}</span>
      </div>

      <div class="form-item">
        <label class="form-label">确认密码</label>
        <input
          type="password"
          v-model="registerForm.confirmPassword"
          placeholder="再次输入密码"
          class="form-input"
          @input="validateConfirmPassword"
        />
        <span v-if="registerErrors.confirmPassword" class="error-text">{{
          registerErrors.confirmPassword
        }}</span>
      </div>

      <button
        class="submit-btn"
        @click="handleRegister"
        :disabled="!canRegister"
      >
        完成注册
      </button>
    </div>

    <!-- 登录表单 -->
    <div v-if="currentTab === 'login'" class="form-card">
      <div class="login-type-switch">
        <button
          class="type-btn"
          :class="{ active: loginType === 'password' }"
          @click="loginType = 'password'"
        >
          密码登录
        </button>
        <button
          class="type-btn"
          :class="{ active: loginType === 'code' }"
          @click="loginType = 'code'"
        >
          验证码登录
        </button>
      </div>

      <div class="form-item">
        <label class="form-label">手机号</label>
        <input
          type="tel"
          v-model="loginForm.phone"
          placeholder="请输入11位手机号"
          maxlength="11"
          class="form-input"
          @input="validatePhone(loginForm.phone, 'login')"
        />
        <span v-if="loginErrors.phone" class="error-text">{{
          loginErrors.phone
        }}</span>
      </div>

      <!-- 密码登录专属项 -->
      <div v-if="loginType === 'password'" class="form-item">
        <label class="form-label">登录密码</label>
        <input
          type="password"
          v-model="loginForm.password"
          placeholder="请输入登录密码"
          class="form-input"
        />
      </div>

      <!-- 验证码登录专属项 -->
      <div v-if="loginType === 'code'" class="form-item">
        <label class="form-label">验证码</label>
        <div class="code-input-group">
          <input
            type="text"
            v-model="loginForm.code"
            placeholder="请输入6位验证码"
            maxlength="6"
            class="form-input code-input"
          />
          <button
            class="send-code-btn"
            @click="sendLoginCode"
            :disabled="loginCountdown > 0 || !isPhoneValid('login')"
          >
            {{ loginCountdown > 0 ? `${loginCountdown}s后重发` : "发送验证码" }}
          </button>
        </div>
      </div>

      <!-- 记住密码（仅密码登录显示） -->
      <div v-if="loginType === 'password'" class="remember-wrap">
        <label class="remember-label">
          <input
            type="checkbox"
            v-model="rememberPassword"
            class="remember-checkbox"
          />
          记住密码（30天）
        </label>
        <button class="forgot-btn" @click="showReset = true">忘记密码？</button>
      </div>

      <button class="submit-btn" @click="handleLogin" :disabled="!canLogin">
        登录账号
      </button>
    </div>

    <!-- 忘记密码弹窗 -->
    <div v-if="showReset" class="reset-modal">
      <div class="modal-content">
        <div class="modal-title">找回密码</div>
        <button class="close-btn" @click="showReset = false">×</button>

        <div class="form-item">
          <label class="form-label">手机号</label>
          <input
            type="tel"
            v-model="resetForm.phone"
            placeholder="请输入绑定的手机号"
            maxlength="11"
            class="form-input"
            @input="validatePhone(resetForm.phone, 'reset')"
          />
        </div>

        <div class="form-item">
          <label class="form-label">验证码</label>
          <div class="code-input-group">
            <input
              type="text"
              v-model="resetForm.code"
              placeholder="请输入验证码"
              maxlength="6"
              class="form-input code-input"
            />
            <button
              class="send-code-btn"
              @click="sendResetCode"
              :disabled="resetCountdown > 0 || !isPhoneValid('reset')"
            >
              {{
                resetCountdown > 0 ? `${resetCountdown}s后重发` : "发送验证码"
              }}
            </button>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">新密码</label>
          <input
            type="password"
            v-model="resetForm.newPassword"
            placeholder="设置新密码"
            class="form-input"
          />
        </div>

        <button class="submit-btn" @click="handleResetPassword">
          确认重置
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";

// 基础状态
const currentTab = ref("register"); // 当前激活的选项卡：register/login
const loginType = ref("password"); // 登录方式：password/code
const showReset = ref(false); // 是否显示忘记密码弹窗

// 注册表单数据
const registerForm = reactive({
  phone: "",
  code: "",
  password: "",
  confirmPassword: "",
});
const registerErrors = reactive({
  phone: "",
  password: "",
  confirmPassword: "",
});
const registerCountdown = ref(0); // 注册验证码倒计时

// 登录表单数据
const loginForm = reactive({
  phone: "",
  password: "",
  code: "",
});
const loginErrors = reactive({
  phone: "",
});
const loginCountdown = ref(0); // 登录验证码倒计时
const rememberPassword = ref(false); // 记住密码

// 找回密码表单数据
const resetForm = reactive({
  phone: "",
  code: "",
  newPassword: "",
});
const resetCountdown = ref(0); // 找回密码验证码倒计时

// 手机号验证通用方法
const validatePhone = (phone, type) => {
  const phoneReg = /^1[3-9]\d{9}$/;
  const errors =
    type === "register" ? registerErrors : type === "login" ? loginErrors : {};

  if (!phone) {
    errors.phone = "请输入手机号";
    return false;
  } else if (!phoneReg.test(phone)) {
    errors.phone = "请输入正确的手机号格式";
    return false;
  } else {
    errors.phone = "";
    return true;
  }
};

// 密码验证（注册）
const validatePassword = (password) => {
  const passwordReg = /^(?=.*[0-9])(?=.*[a-zA-Z]).{6,16}$/;
  if (!password) {
    registerErrors.password = "请设置密码";
  } else if (!passwordReg.test(password)) {
    registerErrors.password = "密码需包含数字和字母，长度6-16位";
  } else {
    registerErrors.password = "";
  }
};

// 确认密码验证（注册）
const validateConfirmPassword = () => {
  if (registerForm.confirmPassword !== registerForm.password) {
    registerErrors.confirmPassword = "两次输入的密码不一致";
  } else {
    registerErrors.confirmPassword = "";
  }
};

// 检查手机号是否有效（用于控制验证码按钮状态）
const isPhoneValid = (type) => {
  const phone =
    type === "register"
      ? registerForm.phone
      : type === "login"
      ? loginForm.phone
      : resetForm.phone;
  return /^1[3-9]\d{9}$/.test(phone);
};

// 注册表单是否可提交
const canRegister = computed(() => {
  return (
    isPhoneValid("register") &&
    registerForm.code.length === 6 &&
    registerForm.password &&
    registerForm.confirmPassword &&
    !registerErrors.password &&
    !registerErrors.confirmPassword
  );
});

// 登录表单是否可提交
const canLogin = computed(() => {
  return (
    isPhoneValid("login") &&
    (loginType.value === "password"
      ? loginForm.password
      : loginForm.code.length === 6)
  );
});

// 切换选项卡
const switchTab = (tab) => {
  currentTab.value = tab;
  // 切换时清空表单错误
  Object.keys(registerErrors).forEach((key) => (registerErrors[key] = ""));
  Object.keys(loginErrors).forEach((key) => (loginErrors[key] = ""));
};

// 发送验证码通用方法（含倒计时）
const startCountdown = (countdownRef) => {
  countdownRef.value = 60;
  const timer = setInterval(() => {
    countdownRef.value--;
    if (countdownRef.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 发送注册验证码
const sendRegisterCode = () => {
  if (!isPhoneValid("register")) return;

  // 模拟接口请求
  console.log(`向${registerForm.phone}发送注册验证码`);
  startCountdown(registerCountdown);
  alert("注册验证码已发送，请注意查收");
};

// 发送登录验证码
const sendLoginCode = () => {
  if (!isPhoneValid("login")) return;

  // 模拟接口请求
  console.log(`向${loginForm.phone}发送登录验证码`);
  startCountdown(loginCountdown);
  alert("登录验证码已发送，请注意查收");
};

// 发送找回密码验证码
const sendResetCode = () => {
  if (!isPhoneValid("reset")) return;

  // 模拟接口请求
  console.log(`向${resetForm.phone}发送找回密码验证码`);
  startCountdown(resetCountdown);
  alert("验证码已发送，请注意查收");
};

// 处理注册
const handleRegister = () => {
  if (!canRegister.value) return;

  // 模拟注册接口请求
  console.log("注册提交数据：", registerForm);
  alert("注册成功！即将跳转到登录页面");
  switchTab("login");
  // 自动填充手机号到登录表单
  loginForm.phone = registerForm.phone;
};

// 处理登录
const handleLogin = () => {
  if (!canLogin.value) return;

  // 模拟登录接口请求
  console.log("登录提交数据：", { ...loginForm, type: loginType.value });

  if (rememberPassword.value) {
    // 记住密码：存储到localStorage
    localStorage.setItem(
      "driver_login_info",
      JSON.stringify({
        phone: loginForm.phone,
        password: loginForm.password,
        expire: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30天有效期
      })
    );
  }

  alert("登录成功！");
};

// 处理密码重置
const handleResetPassword = () => {
  if (!isPhoneValid("reset") || !resetForm.code || !resetForm.newPassword) {
    alert("请完善表单信息");
    return;
  }

  // 模拟重置密码接口请求
  console.log("密码重置数据：", resetForm);
  alert("密码重置成功！请使用新密码登录");
  showReset.value = false;
  loginForm.phone = resetForm.phone;
  switchTab("login");
};

// 页面加载时读取记住的密码
watch(
  currentTab,
  (newVal) => {
    if (newVal === "login" && loginType.value === "password") {
      const savedInfo = localStorage.getItem("driver_login_info");
      if (savedInfo) {
        const { phone, password, expire } = JSON.parse(savedInfo);
        if (Date.now() < expire) {
          loginForm.phone = phone;
          loginForm.password = password;
          rememberPassword.value = true;
        }
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.auth-page {
  max-width: 400px;
  margin: 50px auto;
  padding: 0 20px;
}

.page-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
  color: #333;
}

.tab-container {
  display: flex;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.tab-btn {
  flex: 1;
  padding: 12px 0;
  background: #f9fafb;
  border: none;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-btn.active {
  background: #3b82f6;
  color: white;
}

.form-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 15px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
}

.code-input-group {
  display: flex;
  gap: 10px;
  align-items: stretch; /* 让子元素高度一致 */
}

.code-input {
  flex: 1;
  box-sizing: border-box; /* 确保 padding 和 border 不撑大元素 */
}

.send-code-btn {
  padding: 0 15px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  white-space: nowrap;
  padding: 12px 15px; /* 与输入框内边距保持一致，视觉更协调 */
}
* {
  box-sizing: border-box;
}
.form-card {
  padding: 20px; /* 原25px可适当减小 */
}
.send-code-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
}

.error-text {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #ef4444;
}

.submit-btn {
  width: 100%;
  padding: 14px 0;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.submit-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
}

.submit-btn:not(:disabled):hover {
  background: #2563eb;
}

/* 登录方式切换 */
.login-type-switch {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.type-btn {
  flex: 1;
  padding: 8px 0;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
}

.type-btn.active {
  background: #eff6ff;
  border-color: #3b82f6;
  color: #3b82f6;
}

/* 记住密码区域 */
.remember-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0 25px;
  font-size: 14px;
}

.remember-label {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  cursor: pointer;
}

.forgot-btn {
  background: none;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  padding: 0;
  font-size: 14px;
}

/* 忘记密码弹窗 */
.reset-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.modal-content {
  width: 100%;
  max-width: 350px;
  background: white;
  border-radius: 12px;
  padding: 25px;
  position: relative;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}
</style>

<style scoped>
/* 添加背景容器样式 */
.background-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 背景图片地址 - 可替换为你的图片路径 */
  background-image: url("https://picsum.photos/id/1071/1920/1080");
  background-size: cover; /* 覆盖整个容器 */
  background-position: center; /* 图片居中 */
  background-repeat: no-repeat; /* 不重复 */
  z-index: -1; /* 放在内容下方 */
  filter: brightness(0.9); /* 适当降低亮度，让文字更清晰 */
}

/* 原有样式保持不变，以下仅展示关键修改 */
.auth-page {
  max-width: 400px;
  margin: 50px auto;
  padding: 0 20px;
  position: relative; /* 确保在背景上方 */
}

/* 可以适当加深表单卡片的背景色和阴影，增强层次感 */
.form-card {
  background: rgba(255, 255, 255, 0.95); /* 半透明白色背景 */
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); /* 增强阴影 */
}
</style>
